/**
 * All rights Reserved, Designed By OprCalf
 * Copyright:    Copyright(C) 2016-2020
 * Company       LengYin Ltd.
 */

package com.platform.gateway.common.filter;

import java.nio.charset.Charset;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;

/**
 * @projectName:  platform-gateway
 * @package:      com.platform.gateway.filter
 * @className:    LogsPreFilter.java
 * @description:  前置日志记录
 * @author:       OprCalf
 * @date:         2020年3月27日
 */
@Slf4j
@Component
public class LogsPreFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return Integer.MIN_VALUE + 1;
    }

    @Override
    public boolean shouldFilter() {
        // throw new RuntimeException("传入的类型有误");
        final RequestContext ctx = RequestContext.getCurrentContext();
        // * 当发生异常的时候,不是进行取值
        if (ctx.getThrowable() != null) {
            log.error("{}",
                    ctx.getThrowable().fillInStackTrace());
            if (ctx.sendZuulResponse()) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }

    }

    @Override
    public Object run() {
        try {
            // 获取当前请求的对象
            final RequestContext ctx = RequestContext.getCurrentContext();
            // 获取当前请求的request
            final HttpServletRequest request = ctx.getRequest();
            log.info("请求地址 : {}", request.getRequestURL().toString());
            log.info("请求方法 : {}", request.getMethod());
            // 获取请求的requestParam的参数
            final Map<String, String[]> map = request.getParameterMap();
            if (map != null && map.size() > 0) {
                log.info("请求的RequestParam参数:{}", JSON.toJSONString(map));
            } else {
                log.info("请求的RequestParam参数:没有请求参数");
            }
            // 获取请求的responseBody的值
            final String reqBody = StreamUtils.copyToString(request.getInputStream(), Charset.forName("UTF-8"));
            log.info("请求的RequestBody参数:{}" + reqBody);
        }
        catch (final Exception e) {
            log.error("{}", e);
        }
        return null;
    }

}
